package com.kobe.game_40;

import com.kobe.util.Prime;

/**
 * 
 * The number, 197, is called a circular prime because all rotations of the
 * digits: 197, 971, and 719, are themselves prime.
 * 
 * There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71,
 * 73, 79, and 97.
 * 
 * How many circular primes are there below one million?
 * 
 * 
 */
public class Game35 {
    public static int[] getCircleNumber(int number) {
        char[] numberCharSequence = String.valueOf(number).toCharArray();
        int length = numberCharSequence.length;
        int[] result = new int[length];
        for (int i = 0; i < length; i++) {
            result[i] = getMovedNumber(numberCharSequence, i);
        }
        return result;
    }

    public static int getMovedNumber(char[] numberCharSequence, int offset) {
        StringBuilder sb = new StringBuilder();
        int index = 0;
        for (int i = 0; i < numberCharSequence.length; i++) {
            if (i + offset >= numberCharSequence.length) {
                index = i + offset - numberCharSequence.length;
            } else {
                index = i + offset;
            }
            sb.append(numberCharSequence[index]);
        }
        return Integer.parseInt(sb.toString());
    }

    public static void main(String[] args) {
        int[] million = new int[1000000];
        million[2] = 1;
        int[] circleNumbers;
        for (int i = 3; i < million.length; i = i + 2) {
            if (million[i] == 0) {
                if (Prime.isPrime(i)) {
                    circleNumbers = getCircleNumber(i);
                    if (circleNumbers.length == 1) {
                        if (circleNumbers[0] == i) {
                            million[i] = 1;
                        }
                    } else {
                        boolean isCirlePrime = true;
                        for (int m = 1; m < circleNumbers.length; m++) {
                            if (!Prime.isPrime(circleNumbers[m])) {
                                isCirlePrime = false;
                                break;
                            }
                        }
                        if (isCirlePrime) {
                            for (int m = 0; m < circleNumbers.length; m++) {
                                million[circleNumbers[m]] = 1;
                            }
                        }
                    }
                }
            }
        }
        for (int i = 0; i < million.length; i++) {
            if (million[i] == 1) {
                System.out.println(i);
            }
        }
        int result = 0;
        for (int temp : million) {
            result += temp;
        }
        System.out.println("Result: " + result);
    }
}
